<script lang="ts" setup>
  import { ref, watch ,reactive,onMounted} from "vue"
  import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
  import { getProjectTotalPayList,getProjectPayRecordsyncRecord } from "@/api/projectPayRecord"
  import { usePagination } from "@/hooks/usePagination"
  import useTable from '@/hooks/useTable'
  import handle from './components/handle.vue'
  import CompanySelect from '@/components/CompanySelect/index.vue'
  import { getCompanyList } from "@/api/company"

  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
  const tableData = ref<any>([])
  const dialogVisible = ref<boolean>(false)
  const activeRow = ref<any>()
  const searchFormRef = ref<FormInstance | null>(null)
  const searchData = reactive<any>({
    year: '' // Ensure year is initialized
  })

  const list = ref([])

  const getTableData = () => {
    loading.value = true
    // Convert searchData.year to 'yyyy' format if it matches the specified format
    if (searchData.year && searchData.year instanceof Date) {
      searchData.year = searchData.year.getFullYear().toString(); // Extract the year
    }
    console.log(searchData,'searchData')
    getProjectTotalPayList({
      ...paginationData,
      ...searchData
    }).then((res: any) => {
      paginationData.total = res.totalCount
      tableData.value = res.data
    }).catch(() => {
      tableData.value = []
    }).finally(() => {
      loading.value = false
    })
  }

  const { handleSelectionChange, multipleSelection, handleBatchDelete, handleDelete } = useTable({ getList: getTableData })

  getCompanyList({ currentPage: 1, pageSize: 999999 }).then((res) => {
    list.value = res.data
  })

  const handleUpdate = (row: any) => {
    activeRow.value = row
    dialogVisible.value = true
  }

  const handleAdd = () => {
    activeRow.value = {}
    dialogVisible.value = true
  }

  //关闭操作框
  const closeHandle = () => {
    dialogVisible.value = false
  }

  //搜索操作
  const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  }

  //重置搜索表单
  const resetSearch = () => {
    searchFormRef.value?.resetFields()
    handleSearch()
  }

  //操作完成
  const successHandle = () => {
    dialogVisible.value = false
    getTableData()
  }

  const syncSummaryData = () => {
    if (!searchData.year) {
      ElMessage.warning('请选择年份')
      return
    }

    // 确保年份格式正确
    let year = searchData.year
    if (year instanceof Date) {
      year = year.getFullYear().toString()
    }

    loading.value = true
    getProjectPayRecordsyncRecord({ year }).then(res => {
      ElMessage.success('同步汇总成功')
      getTableData() // 同步成功后刷新表格数据
    }).catch(() => {
      ElMessage.error('同步汇总失败')
    }).finally(() => {
      loading.value = false
    })
  }

  watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
  onMounted(() => {
    if (searchData.year instanceof Date) {
      searchData.year = new Date() // 确保默认为当前年份
    }
  })
</script>

<template>
  <div class="app-container">
      <div class="title-wrapper">项目付款汇总管理</div>
      <div class="page-main">
        <div shadow="never" class="search-wrapper" v-permission="['paymentsummary-search']">
          <div class="search-main">
              <el-form ref="searchFormRef" label-width="90px" :inline="true" label-position="left" :model="searchData">
                <el-form-item prop="year" label="年份">
                  <el-date-picker style="width:150px"
                    v-model="searchData.year"
                    type="year"
                    placeholder="请选择"
                    format="YYYY"
                  />
                </el-form-item>
                <el-form-item prop="companyName" label="所属公司" >
                  <el-input v-model="searchData.companyName" placeholder="请输入所属公司" clearable/>
                </el-form-item>
              </el-form>
          </div>
          <div class="search-btn">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      <div class="toolbar-wrapper">
          <el-button v-permission="['syncTotal']" type="success" @click="syncSummaryData">同步汇总</el-button>
          <el-button v-permission="['paymentsummary-add']" type="primary" @click="handleAdd">新增</el-button>
      </div>

      <div v-loading="loading" class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column sortable prop="companyName" label="所属公司" fixed="left" />
          <el-table-column sortable prop="projectName" label="项目名称" fixed="left" />
          <el-table-column sortable prop="year" label="年份" fixed="left" />
          <el-table-column sortable prop="one" label="一月" />
          <el-table-column sortable prop="two" label="二月" />
          <el-table-column sortable prop="three" label="三月" />
          <el-table-column sortable prop="four" label="四月" />
          <el-table-column sortable prop="five" label="五月" />
          <el-table-column sortable prop="six" label="六月" />
          <el-table-column sortable prop="seven" label="七月" />
          <el-table-column sortable prop="eight" label="八月" />
          <el-table-column sortable prop="nine" label="九月" />
          <el-table-column sortable prop="ten" label="十月" />
          <el-table-column sortable prop="eleven" label="十一月" />
          <el-table-column sortable prop="twelve" label="十二月" />
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <handle
    v-if="dialogVisible"
    title="新增/编辑产品系列"
    :data="activeRow"
    @success="successHandle"
    @cancel="closeHandle"
  />
</template>

<style lang="scss" scoped>

</style>
